import React, { useEffect, useState, useCallback } from 'react';
import { Select, message } from 'antd';
import { handleUpError } from '../utils/errorHandler';
import { SerialService } from '../services/SerialService';

interface SerialDeviceSelectViewProps {
  value?: string;
  onChange?: (value: string) => void;
}

const SerialDeviceSelectView: React.FC<SerialDeviceSelectViewProps> = ({
  value,
  onChange,
}) => {
  const [ports, setPorts] = useState<{ port: string }[]>([]);

  const fetchSerialPorts = useCallback(async () => {
    try {
      const data = await SerialService.fetchPorts();
      const dataArray = Array.isArray(data) ? data : [];
      setPorts(dataArray);
    } catch (error) {
      handleUpError(error);
      message.error('获取串口设备列表失败');
    }
  }, []);

  useEffect(() => {
    fetchSerialPorts();
  }, [fetchSerialPorts]);

  const options = ports.map((port) => ({
    value: port.port,
    label: port.port,
  }));

  return (
    <Select
      showSearch
      placeholder="请选择设备"
      value={value}
      onChange={onChange}
      onFocus={fetchSerialPorts}
      style={{ width: '100%' }}
      allowClear
      optionFilterProp="label"
      filterOption={(input, option) =>
        (option?.label as string).toLowerCase().includes(input.toLowerCase())
      }
      options={options}
    />
  );
};

export default SerialDeviceSelectView;
